<template>
  <div class="auth-container">
    <el-card class="auth-card">
      <template #header>
        <div class="card-header">
          <h2>欢迎回来</h2>
        </div>
      </template>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-position="top"
        @submit.prevent="handleLogin"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="loginForm.email" type="email" placeholder="请输入您的邮箱" size="large" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            show-password
            placeholder="请输入您的密码"
            size="large"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="captchaCode">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captchaCode"
              placeholder="请输入验证码"
              size="large"
              class="captcha-input"
            />
            <div class="captcha-image-wrapper" @click="refreshCaptcha">
              <img v-if="captchaImage" :src="captchaImage" alt="验证码" class="captcha-image" />
              <el-icon v-else class="loading-icon"><Loading /></el-icon>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="auth-button"
            native-type="submit"
            :loading="loading"
            size="large"
          >
            {{ loading ? '登录中...' : '立即登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      <div class="footer-links">
        <router-link to="/register">还没有账户？立即注册</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/auth/user'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { getCaptchaApi, verifyCaptchaApi } from '@/api/auth/captcha'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()

const loginForm = reactive({
  email: '',
  password: '',
  captchaCode: '',
  captchaId: ''
})

const captchaImage = ref('')
const loading = ref(false)

const rules = reactive<FormRules>({
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captchaCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度为4-6位', trigger: 'blur' }
  ]
})

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const res = await getCaptchaApi()
    if (res.code === 200 && res.data) {
      captchaImage.value = res.data.captchaImage
      loginForm.captchaId = res.data.captchaId
      loginForm.captchaCode = ''
    } else {
      ElMessage.error(res.message || '获取验证码失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取验证码失败')
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 先验证验证码
        const captchaRes = await verifyCaptchaApi({
          captchaId: loginForm.captchaId,
          captchaCode: loginForm.captchaCode
        })
        
        if (captchaRes.code !== 200) {
          ElMessage.error(captchaRes.message || '验证码错误')
          refreshCaptcha()
          loading.value = false
          return
        }
        
        // 验证码正确后再进行登录
        await userStore.login({
          email: loginForm.email,
          password: loginForm.password,
          captchaId: loginForm.captchaId,
          captchaCode: loginForm.captchaCode
        })
        console.log('[login] login() resolved, user:', JSON.parse(JSON.stringify(userStore.user || {})))
        ElMessage.success('登录成功！')
        router.replace('/home')
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败，请检查邮箱和密码')
        // 登录失败后刷新验证码
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%);
}

.auth-card {
  width: 100%;
  max-width: 420px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  border: none;
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #5a3e2b;
  font-weight: 600;
}

.el-form-item__label {
  color: #6b4f3a;
  font-weight: 500;
}

.el-input__inner {
  background-color: #fffaf6;
}

.auth-button {
  width: 100%;
  background: linear-gradient(135deg, #e6a23c, #c88c32);
  border: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.auth-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(230, 162, 60, 0.4);
  background: linear-gradient(135deg, #ebac51, #d1963f);
}

.footer-links {
  margin-top: 20px;
  text-align: center;
}

.footer-links a {
  color: #a47e65;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s;
}

.footer-links a:hover {
  color: #5a3e2b;
  text-decoration: underline;
}

.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image-wrapper {
  width: 120px;
  height: 40px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.captcha-image-wrapper:hover {
  border-color: #e6a23c;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.2);
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.loading-icon {
  font-size: 24px;
  color: #999;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>


